#!/bin/bash

NUM_OF_DBFILES=

function ShowUsage {
    echo -e "\n\033[32;1m$0 [init|run]\033[0m"
}

function Quit {
    [ -n "$1" ] && echo -e "\n\033[31;1m ERROR: $1!\033[0m"
    [ -z "$NUM_OF_DBFILES" ] && rm -rf /var/lib/mysql/*
    exit 1
}

function CheckENV {
    [ 'NOT_SET' = "$DB_PASSWORD" ] \
        && Quit 'Not Set ENV "DB_PASSWORD"'
    [ 'NOT_SET' = "$SQL_FILE" ] \
        && Quit 'Not Set ENV "SQL_FILE"'
}

function InitializePV {
    cd /opt/pv || Quit
    for dir in mysql_data mysql_log; do
        mkdir -p $dir || Quit
        chown -R mysql.mysql $dir || Quit
    done
}

function InitializeDB {
    if [ -z "$NUM_OF_DBFILES" ]; then
        echo 'Initializing mysql db ...'
        tar zxpf /opt/mysql-data.tgz -C /var/lib/mysql \
            || Quit 'Untar mysql data failed'
    fi
}

function ImportSql {
    if [ -z "$NUM_OF_DBFILES" ]; then
        echo 'Importing sql file ...'
        wget -O /opt/db_init.sql $SQL_FILE \
            || Quit 'Wget sql file failed'
        sed -i "s/ENV_PASS/$DB_PASSWORD/g" /opt/db_init.sql \
            || Quit 'Modify sql file failed'
        mysql -uroot < /opt/db_init.sql \
            || Quit 'Import sql file failed'
    fi
}

# Start
case "$*" in
    '')
        CheckENV
        InitializePV
        NUM_OF_DBFILES=$(ls /var/lib/mysql)
        InitializeDB
        rm -f /var/run/mysqld/*
        mysqld &
        echo 'Wait 4 seconds to start mysql ...' && sleep 4
        ImportSql
        wait
        ;;
    'init')
        CheckENV
        InitializePV
        NUM_OF_DBFILES=$(ls /var/lib/mysql)
        InitializeDB
        rm -f /var/run/mysqld/*
        mysqld &
        mysql_pid=$!
        echo 'Wait 4 seconds to start mysql ...' && sleep 4
        ImportSql
        kill -15 $mysql_pid
        wait
        ;;
    'run')
        mysqld &
        ;;
    *)
        ShowUsage
        Quit "Unknown arguments \"$*\""
        ;;
esac

